package com.iot.hmi.control;

import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.HBox;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class CustomDateTimePicker extends HBox {

    private DatePicker datePicker;
    private ComboBox<String> timeComboBox;
    private ObjectProperty<LocalDateTime> dateTime;

    public CustomDateTimePicker() {
        datePicker = new DatePicker();
        timeComboBox = new ComboBox<>();
        dateTime = new SimpleObjectProperty<>();

        // 初始化时间选项
        List<String> timeOptions = new ArrayList<>();
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
        for (int hour = 0; hour < 24; hour++) {
            for (int minute = 0; minute < 60; minute += 15) { // 每15分钟一个选项
                timeOptions.add(LocalTime.of(hour, minute).format(timeFormatter));
            }
        }
        timeComboBox.getItems().addAll(timeOptions);

        // 设置默认值为今天的0点0分
        LocalDate today = LocalDate.now();
        LocalDateTime defaultDateTime = LocalDateTime.of(today, LocalTime.MIN);
        setDateTime(defaultDateTime);

        // 绑定日期和时间
        datePicker.valueProperty().addListener((obs, oldDate, newDate) -> {
            if (newDate != null && timeComboBox.getValue() != null) {
                LocalTime selectedTime = LocalTime.parse(timeComboBox.getValue(), timeFormatter);
                dateTime.set(LocalDateTime.of(newDate, selectedTime));
            }
        });

        timeComboBox.valueProperty().addListener((obs, oldTime, newTime) -> {
            if (datePicker.getValue() != null && newTime != null) {
                LocalTime selectedTime = LocalTime.parse(newTime, timeFormatter);
                dateTime.set(LocalDateTime.of(datePicker.getValue(), selectedTime));
            }
        });

        // 设置 ComboBox 的样式
        timeComboBox.setStyle("-fx-pref-width: 100px;"); // 根据需要调整宽度
        datePicker.setStyle("-fx-pref-width: 150px;");
        getChildren().addAll(datePicker, timeComboBox);
    }

    public ObjectProperty<LocalDateTime> dateTimeProperty() {
        return dateTime;
    }

    public LocalDateTime getDateTime() {
        return dateTime.get();
    }

    public void setDateTime(LocalDateTime dateTime) {
        this.dateTime.set(dateTime);
        if (dateTime != null) {
            datePicker.setValue(dateTime.toLocalDate());
            timeComboBox.setValue(dateTime.toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm")));
        }
    }
}
